package com.easy.life.interceptor;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.easy.life.common.Constant;
import com.easy.life.common.R;
import com.easy.life.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
//全局拦截器
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断请求方式，排除OPTIONS请求
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;//通过所有OPTION请求
        }
        //获取请求头中的token信息
        String token = request.getHeader("token");
        R r = new R();

        try {
            JwtUtils.verify(token); //验证token

            return true;
        } catch (SignatureVerificationException e) {
            r.put("msg", Constant.SIGNATURE_INVALID);
            log.error(e.getMessage());
        } catch (TokenExpiredException e) {
            r.put("msg",Constant.TOKEN_EXPIRED);
            log.error(e.getMessage());
        } catch (AlgorithmMismatchException e) {
            r.put("msg",Constant.TOKEN_WRONG_ALGORITHM);
            log.error(e.getMessage());
        } catch (Exception e) {
            r.put("msg",Constant.TOKEN_INVALID);
            log.error(e.getMessage());
        }
        r.put("code",403);
        String json = new ObjectMapper().writeValueAsString(r);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(json);
        return false;
    }

}
